package com.xiaoxing.gongqiju.mvp.ui.utils;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.text.TextUtils;

import com.dothantech.printer.IDzPrinter;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.xiaoxing.gongqiju.mvp.ui.adapter.LiaoCheng_DeviceListAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 小星 QQ:753940262
 * @class describe
 * @time 2018/12/26 0026 9:57
 */
public class PrinterUtil {

    // 用于处理各种通知消息，刷新界面的handler
    private final Handler mHandler = new Handler();
    public PrinterI mPrinterI;
    private Context mContext;
    private List<IDzPrinter.PrinterAddress> pairedPrinters = new ArrayList<IDzPrinter.PrinterAddress>();
    // 状态提示框
    private AlertDialog stateAlertDialog = null;
    // 上次连接成功的设备对象
    private IDzPrinter.PrinterAddress mPrinterAddress = null;
    // 调用IDzPrinter对象的init方法时用到的IDzPrinterCallback对象
    public IDzPrinter.IDzPrinterCallback mCallback = new IDzPrinter.IDzPrinterCallback() {

        /****************************************************************************************************************************************/
        // 所有回调函数都是在打印线程中被调用，因此如果需要刷新界面，需要发送消息给界面主线程，以避免互斥等繁琐操作。

        // 蓝牙适配器状态发生变化时被调用
        @Override
        public void onProgressInfo(IDzPrinter.ProgressInfo arg0, Object arg1) {
            LogUtils.debugEInfo(String.valueOf(arg0));
            if (mPrinterI != null) {
                mPrinterI.onProgressInfo("蓝牙适配器状态发生变化时被调用:==" + String.valueOf(arg0));
            }
        }

        /****************************************************************************************************************************************/

        // 打印机连接状态发生变化时被调用
        @Override
        public void onStateChange(IDzPrinter.PrinterAddress arg0, IDzPrinter.PrinterState arg1) {
            final IDzPrinter.PrinterAddress printer = arg0;
            if (mPrinterI != null) {
                mPrinterI.onStateChange("打印机连接状态发生变化时被调用:==" + String.valueOf(arg0));
            }
            switch (arg1) {
                case Connected:
                case Connected2:
                    // 打印机连接成功，发送通知，刷新界面提示
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            onPrinterConnected(printer);

                        }
                    });
                    break;

                case Disconnected:
                    // 打印机连接失败、断开连接，发送通知，刷新界面提示
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            onPrinterDisconnected();

                        }
                    });
                    break;

                default:
                    break;
            }
        }

        // 打印标签的进度发生变化是被调用
        @Override
        public void onPrintProgress(IDzPrinter.PrinterAddress address, Object bitmapData, IDzPrinter.PrintProgress progress, Object addiInfo) {
            if (mPrinterI != null) {
                mPrinterI.onPrintProgress("打印标签的进度发生变化是被调用:==" + progress);
            }
            switch (progress) {
                case Success:
                    // 打印标签成功，发送通知，刷新界面提示
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            onPrintSuccess();
                            if (mPrinterI != null) {
                                mPrinterI.printSuccess();
                            }
                        }
                    });
                    break;

                case Failed:
                    // 打印标签失败，发送通知，刷新界面提示
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            onPrintFailed();
                            if (mPrinterI != null) {
                                mPrinterI.printFail();
                            }
                        }
                    });
                    break;

                default:
                    break;
            }
        }

        @Override
        public void onPrinterDiscovery(IDzPrinter.PrinterAddress arg0, IDzPrinter.PrinterInfo arg1) {
            LogUtils.debugEInfo(String.valueOf(arg0));
            if (mPrinterI != null) {
                mPrinterI.onPrinterDiscovery("打印标签的进度发生变化是被调用:==" + String.valueOf(arg0));
            }

        }
    };

    public PrinterUtil(Context context) {
        this.mContext = context;
    }

    public void setPrinterI(PrinterI printerI) {
        mPrinterI = printerI;
    }

    // 选择打印机的按钮事件
    @SuppressLint("MissingPermission")
    public boolean selectPrinterCheck() {
        BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
        if (btAdapter == null) {
            ArmsUtils.makeText(mContext, "当前设备不支持蓝牙！");
            return false;
        }
        if (!btAdapter.isEnabled()) {
            ArmsUtils.makeText(mContext, "蓝牙适配器未开启！");

            return false;
        }
        return isPrinterConnected();

    }

    // 判断当前打印机是否连接
    private boolean isPrinterConnected() {
        // 调用IDzPrinter对象的getPrinterState方法获取当前打印机的连接状态
        IDzPrinter.PrinterState state = IDzPrinter.Factory.getInstance().getPrinterState();

        // 打印机未连接
        if (state == null || state.equals(IDzPrinter.PrinterState.Disconnected)) {
            ArmsUtils.makeText(mContext, "打印机未连接，请先连接打印机！");
            pairedPrinters = IDzPrinter.Factory.getAllPrinters();
            new AlertDialog.Builder(mContext).setTitle("选择已绑定的设备").setAdapter(new LiaoCheng_DeviceListAdapter(mContext, pairedPrinters), new DeviceListItemClicker()).show();

            return false;
        }

        // 打印机正在连接
        if (state.equals(IDzPrinter.PrinterState.Connecting)) {
            ArmsUtils.makeText(mContext, "正在连接打印机，请稍候！");
            return false;
        }

        // 打印机已连接
        return true;
    }

    // 连接打印机请求成功提交时操作
    private void onPrinterConnecting(IDzPrinter.PrinterAddress printer, boolean showDialog) {
        // 连接打印机请求成功提交，刷新界面提示
        String txt = printer.shownName;
        if (TextUtils.isEmpty(txt))
            txt = printer.macAddress;
        txt = "正在连接" + '[' + txt + ']';
        txt += "打印机";
        if (showDialog) {
            showStateAlertDialog(txt);
        }
        if (mPrinterI != null) {
            mPrinterI.Connecting(txt);
        }
//        btnConnectDevice.setText(txt);
    }

    // 显示连接、打印的状态提示框
    private void showStateAlertDialog(String str) {
        if (stateAlertDialog != null && stateAlertDialog.isShowing()) {
            stateAlertDialog.setTitle(str);
        } else {
            stateAlertDialog = new AlertDialog.Builder(mContext).setCancelable(false).setTitle(str).show();
        }
    }

    // 连接打印机操作提交失败、打印机连接失败或连接断开时操作
    private void onPrinterDisconnected() {
        // 连接打印机操作提交失败、打印机连接失败或连接断开时，刷新界面提示
        clearAlertDialog();
        if (mPrinterI != null) {
            mPrinterI.connectFail("连接打印机操作提交失败、打印机连接失败或连接断开时，刷新界面提示");
        }
//        ArmsUtils.makeText(mContext, "连接打印机失败！");
//        btnConnectDevice.setText("");
    }

    // 清除连接、打印的状态提示框
    private void clearAlertDialog() {
        if (stateAlertDialog != null && stateAlertDialog.isShowing()) {
            stateAlertDialog.dismiss();
        }
        stateAlertDialog = null;
    }

    // 连接打印机成功时操作
    private void onPrinterConnected(IDzPrinter.PrinterAddress printer) {
        // 连接打印机成功时，刷新界面提示，保存相关信息
        clearAlertDialog();
//        ArmsUtils.makeText(mContext, "连接打印机成功！");
        mPrinterAddress = printer;
        // 调用IDzPrinter对象的getPrinterInfo方法获得当前连接的打印机信息
        String txt = "打印机：";
        txt += IDzPrinter.Factory.getInstance().getPrinterInfo().deviceName + "\n";
        txt += IDzPrinter.Factory.getInstance().getPrinterInfo().deviceAddress;
//        btnConnectDevice.setText(txt);

        if (mPrinterI != null) {
            mPrinterI.connectSuccess(txt);
        }
    }

    // 标签打印成功时操作
    private void onPrintSuccess() {
        // 标签打印成功时，刷新界面提示
        clearAlertDialog();
        ArmsUtils.makeText(mContext, "打印成功！");

    }

    // 打印请求失败或标签打印失败时操作
    private void onPrintFailed() {
        // 打印请求失败或标签打印失败时，刷新界面提示
        clearAlertDialog();
        ArmsUtils.makeText(mContext, "打印失败！");

    }

    public interface PrinterI {


        void onProgressInfo(String info);

        void onStateChange(String info);

        void onPrintProgress(String info);

        void onPrinterDiscovery(String info);

        void connectSuccess(String info);

        void Connecting(String info);

        void connectFail(String info);

        void printSuccess();

        void printFail();
    }

    // 打印机列表的每项点击事件
    private class DeviceListItemClicker implements DialogInterface.OnClickListener {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            IDzPrinter.PrinterAddress printer = pairedPrinters.get(which);
            if (printer != null) {
                // 连接选择的打印机
                if (IDzPrinter.Factory.getInstance().connect(printer)) {
                    // 连接打印机的请求提交成功，刷新界面提示
                    onPrinterConnecting(printer, true);
                    return;
                }
            }

            // 连接打印机失败，刷新界面提示
            onPrinterDisconnected();
        }
    }
}
